{extend name='admin@main'}

{block name="content"}
<form onsubmit="return false;" class="layui-form layui-card" action="{:request()->url()}" data-auto="true" method="post" autocomplete="off">
    <div class="layui-card-body" style="padding-left:40px">

        <fieldset>
            <legend class="color-green font-s14">小区信息</legend>
            <div id="citiesBox" class="layui-form-item">
                <label class="layui-form-label label-required-next">选择街道</label>
                <div class="layui-input-inline margin-bottom-10">
                    <select class="layui-select" name="check_province" data-level="1" lay-filter="cities">
                        <option value="">请选择省</option>
                    </select>
                </div>
                <div class="layui-input-inline margin-bottom-10">
                    <select class="layui-select" name="check_province" data-level="2" lay-filter="cities">
                        <option value="">请选择市</option>
                    </select>
                </div>
                <div class="layui-input-inline margin-bottom-10">
                    <select class="layui-select" name="check_province" data-level="3" lay-filter="cities">
                        <option value="">请选择区域</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">小区名称</label>
                    <div class="layui-input-inline">
                        <input type="text" required autofocus autocomplete="off" class="layui-input" name="village_name" placeholder="请输入小区名称" value='{$vo.village_name|default=""}'>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">经纬度</label>
                    <div class="layui-input-inline">
                        <input type="text" required autofocus autocomplete="off" class="layui-input" name="center" placeholder="请输入经纬度" value='{$vo.center|default=""}'>
                    </div>
                </div>
                <div class="layui-inline">
                    <!--<p class="color-desc">不知道经纬度？<a href="http://api.map.baidu.com/lbsapi/getpoint/index.html" target="_blank">坐标拾取</a></p>-->
                    <p class="color-desc">
                        <!--<a data-title="选择地址" data-modal='{:url("choose_position")}'>选择位置</a>-->
                        <a href="javascript:void(0)" onclick="choosePosition()">选择位置</a>
                    </p>

                </div>
            </div>
        </fieldset>
        <div class="hr-line-dashed"></div>
        <div class="margin-bottom-20"><a onclick="addRuleItem()" class="layui-btn layui-btn-warm">添加楼栋</a></div>
        {assign name='index' value='0'}
        {assign name='is_default' value='1'}
        {assign name='group_title' value='默认楼栋'}
        {include file='cities/house_item'}
        <div data-item-container></div>
    </div>
    <div class="hr-line-dashed"></div>
    <div class="layui-form-item text-center" style="padding-bottom: 15px;">
        <input type='hidden' value='' name='city_id' id="cityId">
        <button class="layui-btn" type='submit'>保存数据</button>
        <button class="layui-btn layui-btn-danger" type='button' data-confirm="确定要取消吗？" data-close>取消编辑</button>
    </div>
</form>
<script>
    window.form.render();
    function choosePosition() {
        window.layer.open({
            type: 2,
            title: '选择地址',
            area: ['750px', '480px'],
            content: '{:url("cleaner/choose_position")}'
        })
    }
    window.form.on('select(cities)',function (data) {
        let level = data.elem.getAttribute('data-level') || '1';
        let value = data.value;
        if(value.length === 0)
        {
            removeSurplus(3);
            return
        }
        document.getElementById("cityId").value = value;
        ajax2cities("{:url('api/v1/address','','')}/" + value,level);
    });
    function ajax2cities(url, level = 0) {
        level++;
        var xmlhttp;
        if(window.XMLHttpRequest)
        {
            xmlhttp = new XMLHttpRequest();
        }
        else
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function()
        {
            if (xmlhttp.readyState===4 && xmlhttp.status===200)
            {
                //请求成功
                let response = JSON.parse(xmlhttp.responseText);
                if(response && response.code === 1)
                {
                    let removeLevel = level - 1;
                    removeSurplus(removeLevel);

                    let cities = response.data;
                    if(cities.length === 0)
                    {
                        //如果返回数据为空
                        return
                    }

                    if(level < 4)
                    {
                        let level_dom = document.querySelector("select[data-level='"+level+"']");
                        for(let i = 0; i < cities.length; i++)
                        {
                            let option = document.createElement("option");
                            option.value = cities[i].id;
                            option.innerText = cities[i].name;
                            level_dom.appendChild(option)
                        }
                    } else {
                        let citiesBox = document.getElementById("citiesBox");
                        let div = document.createElement("div");
                        div.setAttribute('class','layui-input-inline margin-bottom-10');
                        let select = document.createElement("select");
                        select.setAttribute('data-level',level);
                        select.setAttribute('lay-filter','cities');
                        select.setAttribute('class','layui-select');
                        select.setAttribute('name','check_province');
                        let optionNull = document.createElement("option");
                        optionNull.value = "";
                        optionNull.innerText = '请选择';
                        select.appendChild(optionNull);
                        for(let i = 0; i < cities.length; i++)
                        {
                            let option = document.createElement("option");
                            option.value = cities[i].id;
                            option.innerText = cities[i].name;
                            select.appendChild(option)
                        }
                        div.appendChild(select);
                        citiesBox.appendChild(div);

                    }
                    window.form.render();
                }
            }
        };
        xmlhttp.open("GET",url,true);
        xmlhttp.send();
    }

    /**
     * 按级别重置选择框
     * @param level
     */
    function removeSurplus(level) {
        let selectAll = document.getElementsByName('check_province');
        for (let j = 0; j < selectAll.length; j++) {
            // 遍历元素
            let selectLevel = selectAll[j].getAttribute('data-level') || '';
            if(selectLevel > level)
            {
                if(selectLevel > 3)
                {
                    let parentNode = selectAll[j].parentNode;
                    parentNode.remove();
                } else {
                    selectAll[j].innerHTML = "";
                    let optionNull = document.createElement("option");
                    optionNull.value = "";
                    let optionNullText = '';
                    switch(selectLevel) {
                        case "1":
                            optionNullText = '请选择省';
                            break;
                        case "2":
                            optionNullText = '请选择市';
                            break;
                        case "3":
                            optionNullText = '请选择区域';
                            break;
                        default:
                            optionNullText = '请选择';
                    }
                    optionNull.innerText = optionNullText;
                    selectAll[j].appendChild(optionNull);
                }

            }
        }
    }
    (function () {
        ajax2cities("{:url('api/v1/address','','')}/1");
    })();
    function delRuleItem(that) {
        $.msg.confirm('确定要移除吗？', function (index) {
            $(that).parent('fieldset').remove(), $.msg.close(index);
        })
    }
    function addRuleItem() {
        this.itemIndex = $('[data-item-container] fieldset:last').attr('data-max-index') || 0;
        this.html = $('#template').html().replace(/\[index\]/gi, parseInt(this.itemIndex) + 1);
        $('[data-item-container]').append(this.html);
    }
</script>
{assign name='is_default' value='0'}
{assign name='index' value='[index]'}
{assign name='group_title' value='楼栋分组'}
<div class="layui-hide" id="template">
    {include file='cities/house_item'}
</div>
{/block}
